package com.wusuowei.config.rabbitmq;

import com.wusuowei.common.model.po.ComLoginLog;
import com.wusuowei.config.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Slf4j
@Component
@RabbitListener(queues = "${mq.login.queue}")
public class LoginLogConsumer {

//    @Autowired
//    private SysLogininforMapper sysLogininforMapper;

    @Autowired
    JdbcTemplate jdbcTemplate;
    @RabbitHandler
    public void handler(ComLoginLog logininfor) throws Exception {
        try {
            //手动ack 第一个参数是消息的标记，第二个参数代表是false 代表仅仅确认当前消息，为true表示确认之前的所有消息
            //  int i = 1/0;
            String sql = "INSERT INTO `sys_login_log` VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, null);
                    preparedStatement.setString(2, logininfor.getUserName());
                    preparedStatement.setString(3, logininfor.getIpaddr());
                    preparedStatement.setString(4, logininfor.getLoginLocation());
                    preparedStatement.setString(5, logininfor.getBrowser());
                    preparedStatement.setString(6, logininfor.getOs());
                    preparedStatement.setString(7, logininfor.getStatus());
                    preparedStatement.setString(8, logininfor.getMsg());
                    preparedStatement.setString(9, logininfor.getLoginTime().toString());
                    return preparedStatement;
                }
            });
         //   sysLogininforMapper.insert(logininfor);//登录日志记录
            log.info("消息消费成功：{}",logininfor);
        } catch (Exception e) {
            throw new ServiceException(500,e.getMessage());
        }

      //  channel.basicAck(deliveryTag,false);
    }
}
